#!/bin/bash

menu(){
echo " 1.配置主机名"
echo " 2.配置IP"
echo " 3.查看IP和主机名"
echo " 4.退出" 
}

#1.配置主机名
c_hosts(){
	read -p "please input your hostname: " u_hostname
	hostname $u_hostname
	sed -i "/HOSTNAME/c HOSTNAME=$u_hostname" /etc/sysconfig/network

}
#2.配置IP
c_ip(){
	read -p "please input IP: " u_ip
	if (( ${u_ip} == 0 )) &>/dev/null
	then
		echo "不合法，请重新输入"
	elif echo $u_ip|egrep [a-Z]
	then
		echo "不合法，请重新输入"
	elif	echo $u_ip|egrep --color "\b([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-1][0-9]|22[0-3])(\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])){3}\b"
	then
		a=`awk -F= '/IPADDR/{print $2}' /etc/sysconfig/network-scripts/ifcfg-eth0` 
   		sed -i "/IPADDR/c IPADDR=$u_ip" /etc/sysconfig/network-scripts/ifcfg-eth0
		awk '/IPADDR/{print $0}' /etc/sysconfig/network-scripts/ifcfg-eth0
		if (($?==1)) 
		then
			sed -i "/IPADDR/c IPADDR=$a" /etc/sysconfig/network-scripts/ifcfg-eth0
		fi
	else 
		echo "不合法，请重新输入"
		
	fi
}
#3.查看ip和主机名
show_ip_host(){
	cat /etc/sysconfig/network|egrep  "HOSTNAME"
	awk '/IPADDR/{print $0}' /etc/sysconfig/network-scripts/ifcfg-eth0
}

main(){	
	clear
	while true
	do
	menu
	read -p "please choose the option(1-4):" choice
	case $choice in
	1)
		c_hosts
		;;
	2)
		c_ip
		;;
	3)
		show_ip_host
		;;
	4)
		break
		;;
	*)
		break
		;;
	esac
	read -p "please put any key to continue " key
	clear
	done
}
main
		
